package com.xayy.health.mgt.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.kawins.base.result.CheckResult;
import cn.kawins.base.result.ResultBody;
import cn.kawins.mybatis.base.BaseController;
import cn.kawins.mybatis.util.SnowflakeId;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.fastjson.JSONArray;
import com.xayy.health.core.exception.HealthException;
import com.xayy.health.core.listener.CustomAnalysisEventListener;
import com.xayy.health.core.utils.ListUtil;
import com.xayy.health.mgt.model.BatchUploadData;
import com.xayy.health.mgt.model.SatelliteCode;
import com.xayy.health.mgt.model.SatelliteParam;
import com.xayy.health.mgt.model.dto.DataFeatureDto;
import com.xayy.health.mgt.service.BatchUploadDataService;
import com.xayy.health.mgt.service.SatelliteCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.xayy.health.core.listener.MergeExcel.mergeExcelData;

/**
 * @author zhangxa
 */
@RestController
@RequestMapping("/batch-upload")
@Api(tags = "批量上传图例")
public class BatchUploadController extends BaseController<BatchUploadData> {

    @Autowired
    private BatchUploadDataService batchUploadDataService;

    @Autowired
    private  SatelliteController satelliteController;

    @Autowired
    private SatelliteCodeService satelliteCodeService;

    private static final int HEAD_ROW_NUM = 1;


    /**
     * 上传excel
     *
     * @param file          上传文件
     * @param satelliteCode 卫星代号
     * @return ResultBody
     * @throws IOException IO异常
     */
    @PostMapping("upload")
    @ApiOperation(value = "上传excel")
    @ResponseBody
    public ResultBody upload(MultipartFile file, String satelliteCode) throws IOException {
        Long fileLogo = new SnowflakeId().genId("tb_batch_upload_data", "file_logo");
        List<BatchUploadData> excelDataList;
        CustomAnalysisEventListener listener = new CustomAnalysisEventListener(HEAD_ROW_NUM, file, fileLogo, satelliteCode);
        EasyExcel.read(file.getInputStream(), BatchUploadData.class, listener).extraRead(CellExtraTypeEnum.MERGE).sheet().doRead();
        excelDataList = listener.getList();
        int numberOfCurvesNum = ListUtil.sumField(excelDataList, "NumberOfCurves");
        int paramCodeNum = (int) excelDataList.stream().filter(item -> item.getParamCode() != null).count();
        int pictureNum = ListUtil.sumField(excelDataList, "pictureNum");
        int dataTotal = ListUtil.sumField(excelDataList, "dataTotal");
        int legendNameNum = (int) excelDataList.stream().filter(item -> item.getLegendName() != null).count();
        List<String> originalParamCodeList = excelDataList.stream().map(BatchUploadData::getParamCode).collect(Collectors.toList());
        List<String> duplicate = ListUtil.findDuplicate(originalParamCodeList);
        SatelliteCode satelliteCode1 = satelliteCodeService.selectOne(SatelliteCode.builder().satelliteCode(satelliteCode).build());

        List<Object> checkParamList = new ArrayList<>();
        if(CollUtil.isNotEmpty(originalParamCodeList)&&BeanUtil.isNotEmpty(satelliteCode1)){
            String satelliteId = satelliteCode1.getSatelliteId();
            for (String paramCode : originalParamCodeList) {
                ResultBody resultBody = satelliteController.screenParam(Long.valueOf(satelliteId), paramCode,null);
                CheckResult<String> stringCheckResult = resultBody.checkResult();
                List<SatelliteParam> satelliteParamList = JSONArray.parseArray(stringCheckResult.getData(), SatelliteParam.class);
                if (CollUtil.isNotEmpty(satelliteParamList)) {
                    List<SatelliteParam> satelliteParams = satelliteParamList.stream().filter(item -> item.getTelemetryCode().equals(paramCode)).collect(Collectors.toList());
                    if (CollUtil.isEmpty(satelliteParams)) {
                        checkParamList.add(paramCode);
                    }
                } else if (CollUtil.isEmpty(satelliteParamList)) {
                    checkParamList.add(paramCode);
                }
            }
        }

        if(CollUtil.isNotEmpty(checkParamList)){
            throw  new HealthException("excel文件中参数代号"+CollUtil.join(checkParamList,",")+"与图谱提供的参数代号不匹配,请检查参数代号在图谱提供的参数中是否存在。");
        }

        if (dataTotal != paramCodeNum) {
            throw new HealthException("excel文件中存在参数代号和总个数总数不匹配");
        } else if (numberOfCurvesNum != paramCodeNum) {
            throw new HealthException("excel文件中存在参数代号和曲线数量总数不匹配");
        } else if (legendNameNum != pictureNum) {
            throw new HealthException("excel文件中存在图例名称和图片总数不匹配");
        }else if(CollUtil.isNotEmpty(duplicate)){
            throw new HealthException("Excel中参数代号" + CollUtil.join(duplicate, ",") + "重复");
        }
        List<CellExtra> cellExtraList = listener.getCellExtraList();
        if (cellExtraList != null && !cellExtraList.isEmpty()) {
            mergeExcelData(excelDataList, cellExtraList, HEAD_ROW_NUM);
        }
        batchUploadDataService.save(excelDataList);
        return ResultBody.success("上传成功");
    }


    /**
     * 获取上传记录信息
     * @param satelliteName 卫星名称
     * @return ResultBody
     */
    @PostMapping("getUploadList")
    @ApiOperation(value = "获取上传记录信息")
    public ResultBody getUploadList(String satelliteName) {
        return ResultBody.success(batchUploadDataService.getUploadList(satelliteName));
    }

    /**
     * 根据卫星名称文件标识查询图例参数
     * @param fileLogo 文件标识
     * @param satelliteName 卫星名称
     * @return ResultBody
     */
    @GetMapping("getLegendNameList/{fileLogo}/{satelliteName}")
    @ApiOperation(value = "根据卫星名称文件标识查询图例参数")
    public ResultBody getLegendNameList(@PathVariable("fileLogo") Long fileLogo, @PathVariable("satelliteName") String satelliteName) {
        return ResultBody.success(batchUploadDataService.getLegendNameList(fileLogo, satelliteName));
    }


    /**
     * 批量特征分析图表
     * @param dataFeatureDto 特征分析实体
     * @return ResultBody
     */
    @ApiOperation(value = "批量特征分析图表")
    @PostMapping("getBatchFeatureEcharts")
    public ResultBody getBatchFeatureEcharts(@RequestBody DataFeatureDto dataFeatureDto) {
        return batchUploadDataService.getBatchFeatureEcharts(dataFeatureDto).body();
    }

    /**
     * 根据图例名称查询参数代号
     * @param fileLogo 文件标识
     * @param satelliteName 卫星名称
     * @param legendName 图例名称
     * @return ResultBody
     */
    @GetMapping("getParamCodesListByLegendName/{fileLogo}/{satelliteName}/{legendName}")
    @ApiOperation(value = "根据图例名称查询参数代号")
    public ResultBody getParamCodesListByLegendName(@PathVariable("fileLogo") Long fileLogo, @PathVariable("satelliteName") String satelliteName, @PathVariable String legendName) {
        return ResultBody.success(batchUploadDataService.getParamCodesListByLegendName(fileLogo, satelliteName, legendName));
    }

    /**
     * 删除上传记录
     * @param fileLogo 文件标识
     * @return ResultBody
     */
    @DeleteMapping("deleteBatchDataByFileLogo/{fileLogo}")
    @ApiOperation(value = "删除上传记录")
    public ResultBody deleteBatchDataByFileLogo(@ApiParam("excel文件标识") @PathVariable("fileLogo") Long fileLogo) {
        return ResultBody.success(batchUploadDataService.deleteBatchDataByFileLogo(fileLogo));
    }
}
